package cc.rengu.igas.channel.alipay.core.service.trans;

import cc.rengu.igas.channel.alipay.common.constant.AlipayConfigConstant;
import cc.rengu.igas.channel.alipay.common.constant.AlipayParamConstant;
import cc.rengu.igas.channel.alipay.common.constant.AlipayTreeNodeConstant;
import cc.rengu.igas.channel.alipay.common.enums.RespCodeEnum;
import cc.rengu.igas.channel.alipay.core.model.ChnlBizResponse;
import cc.rengu.igas.channel.alipay.core.model.IdcInfo;
import cc.rengu.igas.channel.alipay.core.model.IdcInfoList;
import cc.rengu.igas.channel.alipay.core.service.base.MchntService;
import cc.rengu.igas.channel.alipay.facade.request.IdcQueryRequest;
import cc.rengu.igas.channel.alipay.facade.response.IdcQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.DstChannelCfg;
import cc.rengu.oltp.service.common.entity.DstChannelInfo;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.RedisUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 获取用户OpenId
 */
public class IdcQueryService extends MchntService {
    @Override
    protected Object beforeBizProcess() throws Exception {
        IdcQueryRequest idcQueryRequest = new IdcQueryRequest();
        ConvertUtil.convertOutput(idcQueryRequest);
        return idcQueryRequest;
    }

    @Override
    protected ChnlBizResponse callBizService(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        int iReturnCode = 0;
        String secret = null;
        int timeQuery;
        IdcQueryResponse idcQueryResponse = new IdcQueryResponse();
        IdcQueryRequest idcQueryRequest = (IdcQueryRequest) request;
        String instId = idcQueryRequest.getHeader().getInstId();
        DstChannelInfo dstChannelInfo = (DstChannelInfo) xmlTreeUtil.getXmlTreeObjectValue(AlipayTreeNodeConstant.DST_CHANNEL_INFO, DstChannelInfo.class);
        DstChannelCfg dstChannelCfg = (DstChannelCfg) xmlTreeUtil.getXmlTreeObjectValue(AlipayTreeNodeConstant.DST_CHANNEL_CFG, DstChannelCfg.class);
        xmlTreeUtil.setXmlTreeStringValue(AlipayTreeNodeConstant.ALI_METHOD, "alipay.other.idc.query");
        xmlTreeUtil.setXmlTreeStringValue(AlipayTreeNodeConstant.ALIPAY_APPID, dstChannelCfg.getChannelNo());
        xmlTreeUtil.setXmlTreeStringValue(AlipayTreeNodeConstant.ALIPAY_PID, dstChannelCfg.getProviderMchntNo());
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, idcQueryRequest.getHeader().getTxnNum());

        iReturnCode = schedule.callService(dstChannelInfo.getDstServiceName(), 0);
        if (0 != iReturnCode) {
            rglog.error("调用通道服务<{}>失败，iReturnCode:<{}>", dstChannelInfo.getDstServiceName(), iReturnCode);
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        }
        String code = xmlTreeUtil.getXmlTreeStringValue(AlipayTreeNodeConstant.ALI_RET_CODE);
        String msg = xmlTreeUtil.getXmlTreeStringValue(AlipayTreeNodeConstant.ALI_RET_MSG);
        String subCode = xmlTreeUtil.getXmlTreeStringValue(AlipayTreeNodeConstant.ALI_RET_SUBCODE);
        String subMsg = xmlTreeUtil.getXmlTreeStringValue(AlipayTreeNodeConstant.ALI_RET_SUBMSG);
        ConvertUtil.convertOutput(idcQueryResponse);
        if (!AlipayParamConstant.AILPAY_SUCCESS_CODE.equals(code)) {
            rglog.error("调用第三方服务失败,respCode=[{}],respDesc=[{}]", code, msg);
            idcQueryResponse.setRespCode((null == subCode) ? code : subCode);
            idcQueryResponse.setRespDesc((null == subMsg) ? msg : subMsg);
        } else {
            idcQueryResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            idcQueryResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            IdcInfoList idcInfos = new IdcInfoList();
            ConvertUtil.convertOutput(idcInfos);
            List<String> idcFlagList = new ArrayList<>();
            List<IdcInfo> idcInfoList = idcInfos.getIdcInfos();
            if (null != idcInfoList && idcInfoList.size() > 0) {
                Iterator<IdcInfo> itContact = idcInfoList.iterator();
                while (itContact.hasNext()) {
                    IdcInfo idcInfo = itContact.next();
                    rglog.error("idcFlag=[{}],status[{}]", idcInfo.getIdcFlag(), idcInfo.getStatus());
                    if ("02".equals(idcInfo.getStatus())) {
                        continue;
                    }
                    idcFlagList.add(idcInfo.getIdcFlag());
                }
            }
            idcQueryResponse.setIdcFlagList(idcFlagList);
            if (idcFlagList.size() != 0) {
                SysParamService sysParamService = new SysParamServiceImpl();
                SysParam sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID,
                        AlipayConfigConstant.NUCC_CONF_NODE, AlipayConfigConstant.IDC_QUERY_TIME);
                if (sysParam == null) {
                    rglog.error("为指定配置查询间隔，使用默认间隔时间");
                    timeQuery = AlipayParamConstant.DEFAULT_PAYMENT_VALID_TIME;
                } else {
                    timeQuery = Integer.parseInt(sysParam.getParamKey());
                }
                /*加载idc到redis缓存*/
                RedisUtil.onceSet(AlipayParamConstant.NUCC_IDC_CAC, JSON.toJSONString(idcFlagList), timeQuery);
            }
        }
        ChnlBizResponse chnlBizResponse = new ChnlBizResponse();
        chnlBizResponse.setResult(idcQueryResponse);
        return chnlBizResponse;
    }

    @Override
    protected void afterBizProcess(ChnlBizResponse response) throws Exception {
        IdcQueryResponse idcQueryResponse = (IdcQueryResponse) response.getResult();
        ConvertUtil.convertInput(idcQueryResponse);
    }

}
